/*
 * File: AbstractImportExport.java 
 *  
 * Created on 01.02.2011
 */
package de.graph.impex;

import java.io.File;


public abstract class AbstractImportExport {

    private final String dbPath;
    
    public AbstractImportExport(String dbPath) {
        this(dbPath, false);
    }

    public AbstractImportExport(String dbPath, boolean forceCleanup) {
        if (dbPath == null) {
            throw new IllegalArgumentException("Parameter 'dbPath' must not be null!");
        }
        
        if (forceCleanup) {
            deleteFileOrDirectory(dbPath);
        }

        this.dbPath = dbPath;
        
        registerShutdownHook();
    }

    protected String getDBPath() {
        return dbPath;
    }
    
    protected abstract void shutdown();

    protected final void deleteFileOrDirectory(String pathName) {
        if (pathName != null) {
            deleteFileOrDirectory(new File(pathName));
        }
    }
    
    protected final void deleteFileOrDirectory(File path) {
        if (path != null && path.exists()) {
            if (path.isDirectory()) {
                for (File child : path.listFiles()) {
                    deleteFileOrDirectory(child);
                }
            }
            
            path.delete();
        }
    }
    
    private void registerShutdownHook() {
        // Registers a shutdown hook 
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                shutdown();
            }
        });
    }
}
